//控制层
app.controller('goodsController', function ($scope, $location, $controller, typeTemplateService, uploadService, goodsService, itemCatService) {

    $controller('baseController', {$scope: $scope});//继承

//初始化变量
    $scope.entity = {tbGoods: {}, tbGoodsDesc: {itemImages: [], specificationItems: [],customAttributeItems:[]}};
    //读取列表数据绑定到表单中  
    $scope.findAll = function () {
        goodsService.findAll().success(
            function (response) {
                $scope.list = response;
            }
        );
    }

    //分页
    $scope.findPage = function (page, rows) {
        goodsService.findPage(page, rows).success(
            function (response) {
                $scope.list = response.rows;
                $scope.paginationConf.totalItems = response.totals;//更新总记录数
            }
        );
    }

    //查询实体回显操作
    $scope.findOne = function () {
        var search = $location.search()['id'];
        if (search == null) {
            return;
        }
        goodsService.findOne(search).success(
            function (response) {
                $scope.entity = response;
                if ($scope.entity.tbGoodsDesc == null) {
                    $scope.entity.tbGoodsDesc = {itemImages: [], specificationItems: [],customAttributeItems:[]};
                }else{
                    $scope.entity.tbGoodsDesc.customAttributeItems = JSON.parse($scope.entity.tbGoodsDesc.customAttributeItems);
                    $scope.entity.tbGoodsDesc.itemImages = JSON.parse($scope.entity.tbGoodsDesc.itemImages);
                    $scope.entity.tbGoodsDesc.specificationItems = JSON.parse($scope.entity.tbGoodsDesc.specificationItems);
                    for (var i = 0; i < $scope.entity.itemList.length; i++) {
                        $scope.entity.itemList[i].spec = JSON.parse($scope.entity.itemList[i].spec);
                    }
                }
                try {
                    editor.html($scope.entity.tbGoodsDesc.introduction);
                } catch (e) {
                    editor.html("");
                }



            }
        );
    }

    //添加
    $scope.add = function () {
        $scope.entity.tbGoodsDesc.introduction = editor.html();
        goodsService.add($scope.entity).success(
            function (response) {
                if (response.success) {
                    alert(response.message);
                    //重新查询
                    $scope.reloadList();//重新加载
                } else {
                    alert(response.message);
                }
            }
        );
    }
    //更新
    $scope.update = function () {
        goodsService.update($scope.entity).success(
            function (response) {
                if (response.success) {
                    //重新查询
                    $scope.reloadList();//重新加载
                } else {
                    alert(response.message);
                }
            }
        );
    }


    $scope.deleteById = function () {
        brandService.deleteById($scope.number).success(function (data) {
            if (data.bool) {
                $scope.reloadlist();
            } else {
                alert(data.message);
            }


        })
    }
    $scope.searchEntity = {auditStatus: ""};//定义搜索对象
    $scope.status = ["未审核", "已审核", "审核未通过"];

    //搜索
    $scope.search = function (page, rows) {
        goodsService.search(page, rows, $scope.searchEntity).success(
            function (response) {
                $scope.list = response.rows;
                $scope.paginationConf.totalItems = response.totals;//更新总记录数

            }
        );
    }


    $scope.uploadFile = function () {
        uploadService.uploadFile().success(
            function (response) {
                if (response.success) {
                    //点击上传，图片的url存入
                    $scope.image_entity.url = response.message;

                } else {
                    alert(response.message);
                }
            }
        );
    }


    //图片上传
    $scope.add_image_entity = function () {
        $scope.entity.tbGoodsDesc.itemImages.push($scope.image_entity);
    }
    //删除图片
    $scope.remove_image_entity = function (index) {
        $scope.entity.tbGoodsDesc.itemImages.splice(index, 1);
    };
//查找商品分类信息
    $scope.findByParentId = function (itemId) {
        itemCatService.findByParentId(itemId).success(
            function (response) {
                $scope.itemList_1 = response;
            }
        );
    };
    //一级分类
    $scope.$watch('entity.tbGoods.category1Id', function (newValue, oldValue) {
        $scope.itemList_3 = {};
        itemCatService.findByParentId(newValue).success(
            function (response) {
                $scope.itemList_2 = response;
            }
        );
    });
    //二级分类
    $scope.$watch('entity.tbGoods.category2Id', function (newValue, oldValue) {
        itemCatService.findByParentId(newValue).success(
            function (response) {
                $scope.itemList_3 = response;
            }
        );
    });
    //三级分类
    $scope.$watch('entity.tbGoods.category3Id', function (newValue, oldValue) {
        itemCatService.findOne(newValue).success(
            function (response) {
                $scope.entity.tbGoods.typeTemplateId = response.typeId;
            }
        );
    });

    $scope.typeTemplate = {};
    $scope.$watch('entity.tbGoods.typeTemplateId', function (newValue, oldValue) {
        typeTemplateService.findOne(newValue).success(//查找扩展属性
            function (response) {
                $scope.typeTemplate = response;
                $scope.typeTemplate.specIds = response.specIds;
                var parse = JSON.parse(response.brandIds);
                $scope.typeTemplate.brandIds = parse;
                if ($location.search()['id'] == null) {
                    var parse2 = JSON.parse(response.customAttributeItems);
                    $scope.entity.tbGoodsDesc.customAttributeItems = parse2;
                }
                typeTemplateService.findSpecificationOption($scope.typeTemplate.specIds).success(//查询规格
                    function (response) {
                        //    List<Map>
                        $scope.specificationOptionMap = response;
                    }
                );
            }
        );

    });
    //    attributeName attributeValue  规格名称值    规格属性名称值
    $scope.updateSpecAttribute = function ($event, specName, optionName) {

        var object = $scope.searchObjectByKey($scope.entity.tbGoodsDesc.specificationItems, "attributeName", specName);
        if (object != null) {//有这个规格名称了
            if ($event.target.checked) {
                object.attributeValue.push(optionName);
            } else {
                object.attributeValue.splice(object.attributeValue.indexOf(optionName), 1)
                if (object.attributeValue.length <= 0) {
                    $scope.entity.tbGoodsDesc.specificationItems.splice(
                        $scope.entity.tbGoodsDesc.specificationItems.indexOf(object), 1
                    );
                }
            }
        } else {//没有这个规格名称
            $scope.entity.tbGoodsDesc.specificationItems.push({
                "attributeName": specName,
                "attributeValue": [optionName]
            });
        }
    };


//    创建sku列表
    $scope.createItemList = function () {
        $scope.entity.itemList = [{spec: {}, price: 0, num: 999999, status: '0', isDefault: '0'}];
        var items = $scope.entity.tbGoodsDesc.specificationItems;
        for (var i = 0; i < items.length; i++) {
            $scope.entity.itemList = addColumn($scope.entity.itemList, items[i].attributeName, items[i].attributeValue);
        }
    };

    //                 整个集合      键      值
    addColumn = function (list, columnName, columnvalues) {
        var newList = [];
        for (var i = 0; i < list.length; i++) {
            var oldRow = list[i];
            for (var j = 0; j < columnvalues.length; j++) {
                var newRow = JSON.parse(JSON.stringify(oldRow));
                newRow.spec[columnName] = columnvalues[j];
                newList.push(newRow);
            }
        }
        return newList;

    };
    $scope.itemCatList = [];
//    查询所有的itemCat
    $scope.itemCatFindAll = function () {
        itemCatService.findAllItemList().success(function (response) {
            for (var i = 0; i < response.length; i++) {
                $scope.itemCatList[response[i].id] = response[i].name;
            }
        });
    };
//   复选框回显
    $scope.checkedValues = function (specName, optionName) {
        if ($scope.entity.tbGoodsDesc.specificationItems == null) {
            $scope.entity.tbGoodsDesc.specificationItems = [];
        }
        var list = $scope.entity.tbGoodsDesc.specificationItems;
        var object = $scope.searchObjectByKey(list, 'attributeName', specName);
        if (object != null) {
            var number = object['attributeValue'].indexOf(optionName);
            if (number >= 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    };
    //上架下架
    $scope.isMarketable = function (number,goodsId) {
        goodsService.isMarketable(number, goodsId).success(
            function (response) {
                if (response.success) {
                    $scope.reloadList();
                }else {
                    alert(response.message);
                }

            }
        );
    };
});
